/**
 * API统一封装 - 基于uniCloud云对象
 * 参考request.js的简洁写法模式
 */

// uniCloud云对象调用封装
export const callCloudObject = async (objectName, method, data = {}) => {
  
  try {
    
    // 简化的UniCloud云对象导入方式，避免复杂配置
    const cloudObj = uniCloud.importObject(objectName)
    // 简化调用方式，直接传递数据
    const result = await cloudObj[method](data)
    // 直接返回结果，不做复杂的格式转换
    return result
    
  } catch (error) {
    console.error(`${objectName}.${method} 调用失败:`, error)
    
    // 检查是否为401未授权错误（用户未登录）
    if (error.errCode === 'TOKEN_INVALID_INVALID_TOKEN' || 
        error.errCode === 'TOKEN_INVALID_TOKEN_EXPIRED' || 
        error.errCode === 'TOKEN_INVALID' || 
        error.errCode === 401 || 
        error.code === 401) {
      
      // 获取当前页面路径
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const currentRoute = currentPage ? currentPage.route : '';
      
      // 如果已经在登录页面，则不再跳转，防止循环跳转
      if (currentRoute && currentRoute.indexOf('uni-id-pages/pages/login/') !== -1) {
        throw error;
      }
      
      // 显示提示信息
      uni.showToast({
        title: '登录已过期，请重新登录',
        icon: 'none',
        duration: 2000
      });
      
      // 延迟跳转，让用户看到提示
      setTimeout(() => {
        // 清除登录状态
        uni.removeStorageSync('uni_id_token');
        uni.removeStorageSync('uni_id_token_expired');
        uni.removeStorageSync('uni-id-pages-userInfo');
        uni.removeStorageSync('uni-id-pages-realNameAuth');
        
        // 跳转到登录页面
        uni.reLaunch({
          url: '/uni_modules/uni-id-pages/pages/login/login-withpwd'
        });
      }, 1500);
    }
    
    // 继续抛出错误让上层处理
    throw error
  }
}

// 设备相关API
export const deviceApi = {
  // 获取设备列表
  getDevices: () => callCloudObject('sh_user_device', 'getDeviceList'),
  
  // 添加设备
  addDevice: (data) => callCloudObject('sh_user_device', 'addDevice', data),
  
  // 删除设备
  deleteDevice: (deviceId) => callCloudObject('sh_user_device', 'deleteDevice', { deviceId }),
  
  // 获取设备详情
  getDeviceDetail: (deviceId) => callCloudObject('sh_user_device', 'getDeviceDetail', { deviceId }),
  
  // 更新设备信息
  updateDevice: (deviceId, data) => callCloudObject('sh_user_device', 'updateDevice', { deviceId, ...data }),
  
  // 设备控制指令
  controlDevice: (deviceId, command) => callCloudObject('sh_user_device', 'controlDevice', { deviceId, command }),
  
  // 获取设备状态
  getDeviceStatus: (deviceId) => callCloudObject('sh_user_device', 'getDeviceStatus', { deviceId }),
  
  // 分享设备
  shareDevice: (deviceId, data) => callCloudObject('sh_user_share', 'createDeviceShare', { deviceId, ...data }),
  
  // 取消分享
  unshareDevice: (deviceId, userId) => callCloudObject('sh_user_share', 'removeDeviceShare', { deviceId, userId }),
  
  // 获取设备分享列表
  getDeviceShares: (deviceId) => callCloudObject('sh_user_share', 'getShareList', { deviceId })
}

// 图案相关API
export const patternApi = {
  // 获取图案列表
  getPatternList: (category, page, limit, keyword, sortBy) => 
    callCloudObject('sh_pattern', 'getPatternList', { category, page, limit, keyword, sortBy }),
  
  // 获取图案详情
  getPatternDetail: (patternId) => callCloudObject('sh_pattern', 'getPatternDetail', { patternId }),
  
  // 获取分类列表
  getCategoryList: () => callCloudObject('sh_pattern', 'getCategoryList'),
  
  // 搜索图案
  searchPatterns: (keyword, category, page = 1, limit = 20, sortBy = 'create_time') => 
    callCloudObject('sh_pattern', 'searchPatterns', { keyword, category, page, limit, sortBy }),
  
  // 获取精选图案
  getFeaturedPatterns: (limit = 10) => callCloudObject('sh_pattern', 'getFeaturedPatterns', { limit }),
  
  // 获取热门图案
  getHotPatterns: (limit = 10) => callCloudObject('sh_pattern', 'getHotPatterns', { limit }),
  
  // 获取最新图案
  getNewPatterns: (limit = 10) => callCloudObject('sh_pattern', 'getNewPatterns', { limit }),
  
  // 获取用户收藏图案
  getUserFavorites: (userId, category, page = 1, limit = 20) => 
    callCloudObject('sh_pattern', 'getUserFavorites', { userId, category, page, limit }),
  
  // 切换收藏状态
  togglePatternFavorite: (patternId, action = 'toggle') => 
    callCloudObject('sh_pattern', 'togglePatternFavorite', { patternId, action }),
  
  // 检查是否已收藏
  checkFavorite: (patternId) => callCloudObject('sh_pattern', 'checkFavorite', { patternId })
}

// 收藏相关API
export const favoriteApi = {
  // 获取收藏列表
  getFavorites: (params = {}) => callCloudObject('sh_user_collection', 'getUserCollections', params),
  
  // 添加收藏
  addFavorite: (patternId) => callCloudObject('sh_pattern', 'togglePatternFavorite', { patternId, action: 'add' }),
  
  // 取消收藏
  removeFavorite: (patternId) => callCloudObject('sh_pattern', 'togglePatternFavorite', { patternId, action: 'remove' }),
  
  // 检查是否已收藏
  checkFavorite: (patternId) => callCloudObject('sh_pattern', 'checkFavorite', { patternId })
}

// 播放列表相关API
export const playlistApi = {
  // 获取播放列表
  getPlaylists: (deviceId) => callCloudObject('sh_user_playlist', 'getPlaylists', {deviceId}),
  
  // 添加图案到播放列表
  addToPlaylist: (data) => callCloudObject('sh_user_playlist', 'addPattern', data),
  
  // 批量更新播放列表图案
  updatePlaylistPatterns: (playlistId, patternIds, position = 'append') => 
    callCloudObject('sh_user_playlist', 'updatePlaylistPatterns', { playlistId, patternIds, position }),
  
  // 从播放列表移除图案
  removeFromPlaylist: (playlistId, patternId) => callCloudObject('sh_user_playlist', 'removeFromPlaylist', { playlistId, patternId }),
  
  // 播放播放列表
  playPlaylist: (deviceId, playlistId) => callCloudObject('sh_user_device', 'playPlaylist', { deviceId, playlistId }),
  
  // 设置播放模式
  setPlayMode: (data) => callCloudObject('sh_user_playlist', 'setPlayMode', data),
  
  // 清空播放列表
  clearPlaylist: (data) => callCloudObject('sh_user_playlist', 'clearPlaylist', data),
  
  // 重新排序播放列表中的图案
  reorderPatterns: (data) => callCloudObject('sh_user_playlist', 'reorderPatterns', data)
}

// 热门播放列表相关API
export const featuredPlaylistApi = {
  // 获取热门播放列表
  getFeaturedPlaylists: (params = {}) => {
    const limit = parseInt(params.limit || 4, 10); // 确保 limit 是整数
    return callCloudObject('sh_featured_playlist', 'getFeaturedPlaylists', { limit });
  },
  
  // 获取播放列表详情
  getPlaylistDetail: (id) => callCloudObject('sh_featured_playlist', 'getPlaylistDetail', { id }),
  
  // 添加图案到播放列表（需管理员权限）
  addPatternToPlaylist: (id, patternId) => callCloudObject('sh_featured_playlist', 'addPatternToPlaylist', { id, patternId }),
  
  // 从播放列表移除图案（需管理员权限）
  removePatternFromPlaylist: (id, patternId) => callCloudObject('sh_featured_playlist', 'removePatternFromPlaylist', { id, patternId })
}

// 收藏集相关API
export const collectionApi = {
  // 获取用户收藏集
  getUserCollections: (params = {}) => callCloudObject('sh_user_collection', 'getUserCollections', params),
  
  // 获取收藏集详情
  getCollectionDetail: (collectionId) => callCloudObject('sh_user_collection', 'getCollectionDetail', { collectionId }),
  
  // 创建收藏集
  createCollection: (data) => callCloudObject('sh_user_collection', 'createCollection', data),
  
  // 删除收藏集
  deleteCollection: (collectionId) => callCloudObject('sh_user_collection', 'deleteCollection', { collectionId }),
  
  // 添加图案到收藏集
  addPatternToCollection: (collectionId, patternId) => callCloudObject('sh_user_collection', 'addPatternToCollection', { collectionId, patternId }),
  
  // 从收藏集移除图案
  removePatternFromCollection: (collectionId, patternId) => callCloudObject('sh_user_collection', 'removePatternFromCollection', { collectionId, patternId }),
  
  // 重新排序收藏集中的图案
  reorderPatternsInCollection: (collectionId, patternOrders) => callCloudObject('sh_user_collection', 'reorderPatternsInCollection', { collectionId, patternOrders })
}

// 消息相关API
export const messageApi = {
  // 获取消息列表
  getMessages: (params = {}) => callCloudObject('sh_user_message', 'getMessageList', params),
  
  // 标记消息为已读
  markAsRead: (messageId) => callCloudObject('sh_user_message', 'markMessageAsRead', { messageId }),
  
  // 删除消息
  deleteMessage: (messageId) => callCloudObject('sh_user_message', 'deleteMessage', { messageId }),
  
  // 获取未读消息数量
  getUnreadCount: (data) => callCloudObject('sh_user_message', 'getUnreadCount', data)
}

// 分享相关API
export const shareApi = {
  // 创建设备分享
  createDeviceShare: (deviceId, data) => callCloudObject('sh_user_share', 'createDeviceShare', { deviceId, ...data }),
  
  // 响应分享邀请
  acceptShare: (shareId, inviteCode) => callCloudObject('sh_user_share', 'acceptShare', { shareId, inviteCode }),
  
  // 拒绝分享邀请
  rejectShare: (shareId) => callCloudObject('sh_user_share', 'rejectShare', { shareId }),
  
  // 获取用户的分享邀请
  getUserShareInvites: (status) => callCloudObject('sh_user_share', 'getUserShareInvites', { status }),
}

// 设置相关API
export const settingsApi = {
  // 获取系统设置
  getSettings: () => callCloudObject('settings', 'getSettings'),
  
  // 更新系统设置
  updateSettings: (data) => callCloudObject('settings', 'updateSettings', data),
  
  // 获取应用版本信息
  getVersion: () => callCloudObject('settings', 'getVersion'),
  
  // 反馈意见
  feedback: (data) => callCloudObject('settings', 'feedback', data)
}

// 字典管理相关API
export const dictApi = {
  // 获取字典类型列表
  getDictTypes: () => callCloudObject('sh_dict', 'getDictTypes'),
  
  // 获取字典数据列表
  getDictItems: (type) => callCloudObject('sh_dict', 'getDictItems', { type }),
  
  // 获取图案分类列表
  getPatternCategories: () => callCloudObject('sh_dict', 'getPatternCategories'),
  
  // 获取热门播放列表类型
  getFeaturedPlaylistTypes: () => callCloudObject('sh_dict', 'getFeaturedPlaylistTypes'),
  
  // 创建字典类型（管理员）
  createDictType: (data) => callCloudObject('sh_dict', 'createDictType', data),
  
  // 创建字典数据（管理员）
  createDictItem: (data) => callCloudObject('sh_dict', 'createDictItem', data)
}
